<template>
  <div class="music-home">
    <!-- 顶部导航 -->
    <nav class="music-nav">
      <div class="nav-left">
        <span class="music-icon">🎵</span>
        <h1>网易云音乐</h1>
      </div>
      <div class="nav-links">
        <a href="#" class="active">主页</a>
        <a href="#">排行榜</a>
        <a href="#">歌单</a>
        <a href="#">歌手</a>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-container">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索歌曲、歌手、专辑..."
            class="search-input"
            @keyup.enter="handleSearch"
          >
          <button class="search-btn" @click="handleSearch">
            🔍
          </button>
        </div>
        
        <!-- 搜索结果下拉框 -->
        <div v-if="searchResults.length > 0 && isSearching" class="search-results">
          <div v-for="song in searchResults" :key="song.id" class="search-result-item" @click="playSearchSong(song)">
            <div class="song-info">
              <div class="song-name">{{ song.title }}</div>
              <div class="song-artist">{{ song.artist }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="user-section">
        <div v-if="isLoggedIn" class="user-info">
          <span class="user-name">{{ username }}</span>
          <button class="btn-logout" @click="handleLogout">退出登录</button>
        </div>
        <div v-else class="login-actions">
          <button class="btn-login" @click="showLoginModal = true">登录</button>
          <button class="btn-register" @click="showLoginModal = true; switchToRegister = true">注册</button>
        </div>
      </div>
    </nav>

    <!-- 主内容区 -->
    <main class="music-content">
      <!-- 音乐播放器 -->
      <section class="player-section">
        <MusicPlayer />
      </section>

      <!-- 播放列表 -->
      <section class="playlist-section">
        <MusicList />
      </section>

      <!-- 排行榜 -->
      <section class="ranking-section">
        <MusicRanking />
      </section>

      <!-- 推荐歌曲 -->
      <section class="recommended-section">
        <h2 class="section-title">热门推荐</h2>
        <div class="recommended-grid">
          <div v-for="song in recommendedSongs" :key="song.id" class="song-card" @click="playRecommendedSong(song)">
            <div class="song-card-cover" :style="{ backgroundImage: `url(${song.cover})` }"></div>
            <h4 class="song-card-title">{{ song.title }}</h4>
            <p class="song-card-artist">{{ song.artist }}</p>
          </div>
        </div>
      </section>
    </main>

    <!-- 页脚 -->
    <footer class="music-footer">
      <p>&copy; 2024 网易云音乐 - 让音乐陪伴你的每一天</p>
    </footer>
  </div>
  
  <!-- 登录/注册模态框 -->
  <div v-if="showLoginModal" class="modal-overlay" @click="closeModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ switchToRegister ? '网易云音乐用户注册' : '网易云音乐用户登录' }}</h3>
        <button class="btn-close" @click="closeModal">&times;</button>
      </div>
      
      <div class="avatar-container">
        <img 
          :src="userAvatar" 
          alt="用户头像" 
          class="user-avatar" 
          :class="{ 'avatar-hover': !switchToRegister }"
          @click="changeAvatar"
        >
        <span class="avatar-hint">{{ !switchToRegister ? '点击可切换头像' : '注册后可设置头像' }}</span>
      </div>
      
      <div v-if="!switchToRegister" class="modal-body">
        <div class="form-group">
          <label for="login-username">用户名</label>
          <input
            type="text"
            id="login-username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            required
          />
        </div>
        <div class="form-group">
          <label for="login-password">密码</label>
          <input
            type="password"
            id="login-password"
            v-model="loginForm.password"
            placeholder="请输入密码"
            required
          />
        </div>
        <div class="form-options">
          <label class="checkbox-label">
            <input type="checkbox" v-model="loginForm.rememberMe" />
            <span>记住我</span>
          </label>
        </div>
        <button class="btn-submit" :disabled="loginLoading" @click="handleLogin">
          {{ loginLoading ? '登录中...' : '登录' }}
        </button>
        <div class="form-footer">
          <span>还没有账号？</span>
          <a href="#" @click.prevent="switchToRegister = true">立即注册</a>
        </div>
      </div>
      
      <div v-else class="modal-body">
        <div class="form-group">
          <label for="reg-username">用户名</label>
          <input
            type="text"
            id="reg-username"
            v-model="registerForm.username"
            placeholder="请设置用户名"
            required
          />
        </div>
        <div class="form-group">
          <label for="reg-email">邮箱</label>
          <input
            type="email"
            id="reg-email"
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            required
          />
        </div>
        <div class="form-group">
          <label for="reg-password">密码</label>
          <input
            type="password"
            id="reg-password"
            v-model="registerForm.password"
            placeholder="请设置密码"
            required
          />
        </div>
        <button class="btn-submit" :disabled="regLoading" @click="handleRegister">
          {{ regLoading ? '注册中...' : '注册' }}
        </button>
        <div class="form-footer">
          <span>已有账号？</span>
          <a href="#" @click.prevent="switchToRegister = false">返回登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import MusicPlayer from '../components/MusicPlayer.vue'
import MusicList from '../components/MusicList.vue'
import MusicRanking from '../components/MusicRanking.vue'
import { useMusicStore } from '../stores/music.js'
import { ref, onMounted } from 'vue'

const store = useMusicStore()

// 登录相关状态
const isLoggedIn = ref(false)
const username = ref('')
const showLoginModal = ref(false)
const switchToRegister = ref(false)
const userAvatar = ref('https://picsum.photos/seed/user123/200/200')
const avatarOptions = [
  'https://picsum.photos/seed/user1/200/200',
  'https://picsum.photos/seed/user2/200/200',
  'https://picsum.photos/seed/user3/200/200',
  'https://picsum.photos/seed/user4/200/200',
  'https://picsum.photos/seed/user5/200/200'
]

// 搜索相关状态
const searchQuery = ref('')
const searchResults = ref([])
const isSearching = ref(false)

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false
})

// 注册表单数据
const registerForm = ref({
  username: '',
  email: '',
  password: ''
})

// 加载状态
const loginLoading = ref(false)
const regLoading = ref(false)

// 推荐歌曲数据
const recommendedSongs = ref([
  {
    id: 101,
    title: '夏天的风',
    artist: '温岚',
    cover: 'https://picsum.photos/seed/rec1/300/300'
  },
  {
    id: 102,
    title: '你的答案',
    artist: '阿冗',
    cover: 'https://picsum.photos/seed/rec2/300/300'
  },
  {
    id: 103,
    title: '起风了',
    artist: '买辣椒也用券',
    cover: 'https://picsum.photos/seed/rec3/300/300'
  },
  {
    id: 104,
    title: '像鱼',
    artist: '王贰浪',
    cover: 'https://picsum.photos/seed/rec4/300/300'
  }
])

// 播放推荐歌曲
const playRecommendedSong = (song) => {
  // 检查歌曲是否已在播放列表中
  const existingSongIndex = store.playlist.findIndex(item => item.id === song.id)
  
  if (existingSongIndex >= 0) {
    // 如果已存在，则直接播放
    store.currentIndex = existingSongIndex
    store.isPlaying = true
  } else {
    // 如果不存在，则添加到播放列表并播放
    const songWithUrl = {
      ...song,
      url: `https://example.com/${song.id}.mp3` // 实际项目中替换为真实的音乐文件URL
    }
    store.addSong(songWithUrl)
    store.currentIndex = store.playlist.length - 1
    store.isPlaying = true
  }
  
  // 通知播放器组件更新
  window.dispatchEvent(new Event('songChanged'))
}

// 处理搜索
const handleSearch = () => {
  if (searchQuery.value.trim() === '') {
    searchResults.value = []
    isSearching.value = false
    return
  }

  // 特殊处理：当输入"周杰伦"时显示"csgo"
  if (searchQuery.value.trim() === '周杰伦') {
    // 清除现有搜索状态
    searchResults.value = []
    isSearching.value = false
    
    // 创建一个临时div来显示"csgo"文字
    const div = document.createElement('div')
    div.style.position = 'fixed'
    div.style.top = '50%'
    div.style.left = '50%'
    div.style.transform = 'translate(-50%, -50%)'
    div.style.fontSize = '36px'
    div.style.fontWeight = 'bold'
    div.style.color = '#e53e3e'
    div.style.backgroundColor = 'white'
    div.style.padding = '20px 40px'
    div.style.borderRadius = '8px'
    div.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.1)'
    div.style.zIndex = '9999'
    div.textContent = 'csgo'
    
    document.body.appendChild(div)
    
    // 3秒后移除这个div
    setTimeout(() => {
      document.body.removeChild(div)
    }, 3000)
    
    // 清空搜索框
    searchQuery.value = ''
    return
  }

  // 模拟搜索延迟
  isSearching.value = true
  
  // 过滤匹配的歌曲
  searchResults.value = recommendedSongs.value.filter(song => 
    song.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    song.artist.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
}

// 播放搜索结果中的歌曲
const playSearchSong = (song) => {
  // 检查歌曲是否已在播放列表中
  const existingSongIndex = store.playlist.findIndex(item => item.id === song.id)
  
  if (existingSongIndex >= 0) {
    // 如果已存在，则直接播放
    store.currentIndex = existingSongIndex
    store.isPlaying = true
  } else {
    // 如果不存在，则添加到播放列表并播放
    const songWithUrl = {
      ...song,
      url: `https://example.com/${song.id}.mp3` // 实际项目中替换为真实的音乐文件URL
    }
    store.addSong(songWithUrl)
    store.currentIndex = store.playlist.length - 1
    store.isPlaying = true
  }
  
  // 通知播放器组件更新
  window.dispatchEvent(new Event('songChanged'))
  
  // 清除搜索状态
  searchResults.value = []
  isSearching.value = false
  searchQuery.value = ''
}

// 点击页面其他地方关闭搜索结果
document.addEventListener('click', (e) => {
  if (!e.target.closest('.search-section')) {
    isSearching.value = false
  }
})

import { useRouter } from 'vue-router'

// 添加路由实例
const router = useRouter()

// 处理登录
const handleLogin = async () => {
  loginLoading.value = true
  
  try {
    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 验证用户名和密码
    if (loginForm.value.username === 'zhengbofu' && loginForm.value.password === '123456') {
      // 登录成功
      console.log('登录成功', loginForm.value)
      
      // 设置登录状态
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('username', loginForm.value.username)
      
      // 更新状态
      isLoggedIn.value = true
      username.value = loginForm.value.username
      showLoginModal.value = false
      
      // 记住用户逻辑
      if (loginForm.value.rememberMe) {
        localStorage.setItem('rememberMe', 'true')
      } else {
        localStorage.removeItem('rememberMe')
      }
      
      // 重置表单
      loginForm.value = {
        username: '',
        password: '',
        rememberMe: false
      }
      
      // 登录成功后跳转到个人主页
      router.push('/profile')
    } else {
      // 登录失败
      throw new Error('用户名或密码错误')
    }
  } catch (error) {
      console.error('登录失败', error)
      alert('用户名或密码错误，请重试')
    } finally {
    loginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  regLoading.value = true
  
  try {
    // 模拟注册请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟注册成功
    console.log('注册成功', registerForm.value)
    alert('注册成功，请登录')
    
    // 切换回登录模式
    switchToRegister.value = false
    
    // 重置注册表单
    registerForm.value = {
      username: '',
      email: '',
      password: ''
    }
  } catch (error) {
    console.error('注册失败', error)
    alert('注册失败，请重试')
  } finally {
    regLoading.value = false
  }
}

// 处理退出登录
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    // 清除登录状态
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('username')
    
    // 更新状态
    isLoggedIn.value = false
    username.value = ''
    
    // 可以在这里进行其他清理工作
    alert('已成功退出登录')
  }
}

// 关闭模态框
const closeModal = () => {
  showLoginModal.value = false
  switchToRegister.value = false
  
  // 重置表单
  loginForm.value = {
    username: '',
    password: '',
    rememberMe: false
  }
  registerForm.value = {
    username: '',
    email: '',
    password: ''
  }
}

// 切换头像
const changeAvatar = () => {
  if (!switchToRegister.value) {
    const currentIndex = avatarOptions.findIndex(avatar => avatar === userAvatar.value)
    const nextIndex = (currentIndex + 1) % avatarOptions.length
    userAvatar.value = avatarOptions[nextIndex]
  }
}

// 组件挂载时，检查是否已登录
onMounted(() => {
  const savedIsLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const savedUsername = localStorage.getItem('username')
  
  if (savedIsLoggedIn && savedUsername) {
    isLoggedIn.value = true
    username.value = savedUsername
  }
})
</script>

<style scoped>
.music-home {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #e53e3e 0%, #c53030 100%);
  color: #333;
}

/* 导航样式 */
.music-nav {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.music-icon {
  font-size: 32px;
}

.logo h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
    background: linear-gradient(135deg, #e53e3e 0%, #c53030 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }

.nav-links {
  display: flex;
  gap: 25px;
}

.nav-links a {
  text-decoration: none;
  color: #666;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
}

.nav-links a:hover {
    color: #e53e3e;
  }

  .nav-links a.active {
    color: #e53e3e;
  }

  .nav-links a.active::after {
    content: '';
    position: absolute;
    bottom: -5px;
    left: 0;
    width: 100%;
    height: 2px;
    background: #e53e3e;
    border-radius: 1px;
  }

/* 主内容样式 */
.music-content {
  flex: 1;
  padding: 40px 20px;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 40px;
}

.player-section,
.playlist-section,
.ranking-section,
.recommended-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 25px;
  color: #333;
  text-align: center;
}

/* 推荐歌曲网格 */
.recommended-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.song-card {
  background: white;
  border-radius: 12px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.song-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.song-card-cover {
  width: 100%;
  aspect-ratio: 1;
  border-radius: 10px;
  background-size: cover;
  background-position: center;
  margin-bottom: 15px;
  transition: transform 0.3s ease;
}

.song-card:hover .song-card-cover {
  transform: scale(1.05);
}

.song-card-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-card-artist {
  font-size: 14px;
  color: #666;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 页脚样式 */
.music-footer {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20px;
  text-align: center;
  color: #666;
  font-size: 14px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.music-footer p {
  margin: 0;
}

/* 用户部分样式 */
.user-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.login-actions {
  display: flex;
  gap: 10px;
}

.btn-login,
.btn-register,
.btn-logout {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-login {
    background: #e53e3e;
    color: white;
  }

  .btn-login:hover {
    background: #c53030;
    transform: translateY(-1px);
  }

  .btn-register {
    background: #fff5f5;
    color: #e53e3e;
    border: 1px solid #fed7d7;
  }

.btn-register:hover {
  background: #edf2f7;
  transform: translateY(-1px);
}

.btn-logout {
  background: #f56565;
  color: white;
}

.btn-logout:hover {
  background: #e53e3e;
  transform: translateY(-1px);
}

/* 头像样式 */
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.user-avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #e53e3e;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

.avatar-hover {
  cursor: pointer;
}

.avatar-hover:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-hint {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
  text-align: center;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 450px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.btn-close:hover {
  background: #f7fafc;
}

/* 表单样式 */
.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
    outline: none;
    border-color: #e53e3e;
    box-shadow: 0 0 0 3px rgba(229, 62, 62, 0.1);
  }

.form-options {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-label input[type="checkbox"] {
  width: auto;
  margin: 0;
}

.btn-submit {
    width: 100%;
    padding: 12px;
    background: #e53e3e;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .btn-submit:hover:not(:disabled) {
    background: #c53030;
    transform: translateY(-1px);
  }

.btn-submit:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

.form-footer {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}

.form-footer a {
    color: #e53e3e;
    text-decoration: none;
    margin-left: 4px;
    font-weight: 500;
  }

.form-footer a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-links {
    gap: 15px;
  }
  
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .music-content {
    padding: 20px 15px;
    gap: 25px;
  }
  
  .player-section,
  .playlist-section,
  .recommended-section {
    padding: 20px;
  }
  
  .user-section {
    flex-direction: column;
    gap: 10px;
  }
  
  .modal-content {
    margin: 20px;
  }
}
</style>